package com.txm.applicationListener;

import com.qiniu.storage.BucketManager;
import com.qiniu.util.Auth;
import common.util.UploadUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Created by tangxinmao on 2016/11/3.
 */

@Configuration
public class SpringApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    public static Logger logger = LogManager.getLogger(SpringApplicationListener.class.getName());
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {//root application context 没有parent，他就是老大.
            try {
                //将系统配置文件加载到内存
                Properties properties = PropertiesLoaderUtils.loadAllProperties("/property/common-message.properties");
                Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
                for (Map.Entry<Object, Object> entry : entrySet) {
                    redisTemplate.boundHashOps("properties").put(entry.getKey(), entry.getValue());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将系统参数注入到uploadutil
            String accessKey = redisTemplate.opsForHash().get("properties", "accessKey").toString();
            String secretkey = redisTemplate.opsForHash().get("properties", "secretKey").toString();
            UploadUtil.setBucketName(redisTemplate.opsForHash().get("properties", "bucketName").toString());
            Auth auth = Auth.create(accessKey, secretkey);
            UploadUtil.setAuth(auth);
            UploadUtil.setBucketManager(new BucketManager(auth, UploadUtil.getConfiguration()));
            //清空session
            redisTemplate.delete("sessionIds");
            //初始化一周的访问数据和访问总量
            if (redisTemplate.opsForList().size("weekPV") == 0) {
                redisTemplate.boundListOps("weekPV").rightPushAll("0", "0", "0", "0", "0", "0", "0");
                //临时保存前一天的访问总量
                redisTemplate.boundValueOps("PV").set("0");
            }
        }
    }
}